<template>
  <div class="app-container">
    <el-form label-width="auto">
      <el-row>
        <el-col :span="8">
          <el-form-item label="統計周期">
            <div class="block">
              <el-date-picker
                v-model="startEndTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="開始日期"
                end-placeholder="結束日期"
                :picker-options="pickerOptions"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交貨時間">
            <el-input v-model="leadTime" style="width: 200px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供應商">
            <el-select
              v-model="vendorId"
              clearable
              placeholder="請輸入關鍵詞"
              filterable
            >
              <el-option
                v-for="item in vendorList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品分類">
            <el-cascader
              ref="cascader"
              v-model="selectProductCateValue"
              filterable
              clearable
              :options="productCateOptions"
              style="width: 200px;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否上架">
            <el-select
              v-model="publishStatus"
              placeholder="是否上架"
              clearable
              class="filter-item"
            >
              <el-option
                v-for="item in dict.publishStatus"
                :key="item.id"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="height: 40px;">
        <el-button type="success" size="small" @click="searchData">統計BSL</el-button>
        <el-button type="warning" size="small" :loading="exportLoading" @click="exportExcel">導出BSL</el-button>
        <el-button type="primary" size="small" @click="importPurchase">導入采購單</el-button>
      </div>
    </el-form>
    <el-table v-loading="loading" stripe :data="tableData" @selection-change="selectionChangeHandler" @sort-change="sortChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="productName" label="產品名稱" width="250" show-tooltip-when-overflow />
      <el-table-column prop="sku" label="產品編號" sortable/>
      <el-table-column prop="upc" label="UPC" />
      <el-table-column prop="productCategory" label="產品種類" />
      <el-table-column prop="vendor" label="供應商" width="200" show-tooltip-when-overflow />
      <el-table-column prop="sales" label="總銷量" />
      <el-table-column prop="weekSales" label="周銷量" />
      <el-table-column prop="bsl" label="BSL" />
      <el-table-column prop="cost" label="Cost" />
      <el-table-column prop="price" label="Price" />
      <el-table-column prop="pr" label="PR" />
      <el-table-column prop="stock" label="庫存量" />
      <el-table-column prop="outStock" label="缺貨數量" />
    </el-table>
    <!--分页组件-->
    <el-pagination
      :current-page.sync="currentPage"
      :page-size.sync="size"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 100, 200, 500]"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import api from '@/api/fms/report'
import vendorApi from '@/api/cms/vendor'
import { getTree } from '@/api/pms/productCategory'
import { downloadFile } from '@/utils'

export default {
  name: 'Report',
  dicts: ['publishStatus'],
  data() {
    return {
      exportLoading: false,
      tableData: [],
      vendorOptions: [],
      productCategoryOptions: [],
      tableSelection: [],
      vendorId: '',
      publishStatus: null,
      purchaseProductCategoryId: '',
      vendorList: [],
      productCategoryList: [],
      leadTime: 0.5,
      startEndTime: '',
      selectProductCateValue: [],
      productCateOptions: [],
      loading: false,
      sort: 'id:desc,productCategoryId:desc',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一個月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三個月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      page: 1,
      size: 20,
      currentPage: null,
      total: null
    }
  },
  created() {
    this.getProductCateList()
    this.searchVendor()
  },
  methods: {
    /* 获取商品分类树形*/
    getProductCateList() {
      getTree().then(response => {
        const list = response.data
        this.productCateOptions = []
        for (let i = 0; i < list.length; i++) {
          const children = []
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ value: list[i].children[j].id, label: list[i].children[j].label })
            }
          }
          this.productCateOptions.push({ value: list[i].id, label: list[i].label, children: children })
        }
      })
    },
    searchData() {
      if (this.startEndTime === '') {
        this.$message.warning('統計周期不能為空')
        return
      }
      this.loading = true
      const date = new Date(this.startEndTime[0])
      const startTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
        date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
      const date1 = new Date(this.startEndTime[1])
      const endTime = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' +
        date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
      this.startEndTime.toString().split('')
      api.report({
        'leadTime': this.leadTime,
        'productCategoryId': this.selectProductCateValue[1],
        'vendorId': this.vendorId,
        'startTime': startTime,
        'endTime': endTime,
        'publishStatus': this.publishStatus,
        page: this.page,
        size: this.size,
        sort: this.sort
      }).then((res) => {
        this.tableData = res.data.rows
        this.loading = false
        this.currentPage = this.page
        this.total = res.data.total
      })
    },
    searchVendor() {
      vendorApi.getAll().then(res => {
        for (let i = 0; i < res.data.length; i++) {
          this.vendorList.push({ label: res.data[i].name, value: res.data[i].id })
        }
      })
    },
    exportExcel() {
      if (this.startEndTime === '') {
        this.$message.warning('統計周期不能為空')
        return
      }
      this.exportLoading = true
      const date = new Date(this.startEndTime[0])
      const startTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
        date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
      const date1 = new Date(this.startEndTime[1])
      const endTime = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' +
        date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
      this.startEndTime.toString().split('')
      api.exportBsl({
        'leadTime': this.leadTime,
        'productCategoryId': this.selectProductCateValue[1],
        'vendorId': this.vendorId,
        'startTime': startTime,
        'endTime': endTime,
        'publishStatus': this.publishStatus,
        page: this.page,
        size: this.size,
        sort: this.sort
      }).then((res) => {
        downloadFile(res, 'BSL報表', 'xlsx')
        this.exportLoading = false
        this.$message.success('導出成功')
      })
    },
    importPurchase() {
      this.$router.push({
        path: '/erp/creatPurchase/' + 'add',
        name: 'CreatPurchase',
        params: { products: JSON.parse(JSON.stringify(this.tableSelection)), id: 'add', vendorId: this.vendorId }
      })
    },
    selectionChangeHandler(sel) {
      this.tableSelection = sel
    },
    handleSizeChange(val) {
      this.size = val
      this.searchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.searchData()
    },
    sortChange(column) {
      const sortColumn = column.prop
      if (column.order === 'ascending') {
        this.sort = sortColumn + ':asc'
      }
      if (column.order === 'descending') {
        this.sort = sortColumn + ':desc'
      }
      this.searchData()
    }
  }
}
</script>

<style scoped>

</style>
